package com.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.apache.log4j.Logger;

public class CustomFilter implements Filter {
	private FilterConfig filterConfig = null;
	public static final Logger logger = Logger.getLogger(CustomFilter.class);


	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (filterConfig == null)
			return;
		
		ResponseWrapper wrapper = new ResponseWrapper(
				(HttpServletResponse) response);

		chain.doFilter(request, wrapper);

	}

	class ResponseWrapper extends HttpServletResponseWrapper {
		private ByteArrayOutputStream buffer = null;
		private PrintWriter writer = null;

		public ResponseWrapper(HttpServletResponse response) throws IOException {
			super(response);
			this.buffer = new ByteArrayOutputStream();
			this.writer = response.getWriter();
		}

		public PrintWriter getWriter()  {
			
			try {
				
				String message = "<responseData>error</responseData>";
				this.buffer.write(message.getBytes());
				this.writer = new PrintWriter(new OutputStreamWriter(buffer, getCharacterEncoding()));
			} catch (UnsupportedEncodingException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			}
			return writer;
		}
	}

}
